package com.example.login_captcha_2.controller;

import com.example.login_captcha_2.consts.RedisKeyPrefixes;
import com.example.login_captcha_2.exception.GlobalException;
import com.example.login_captcha_2.property.CaptchaImageProperties;
import com.example.login_captcha_2.redis.StringRedisUtils;
import com.example.login_captcha_2.restful.ResponseCode;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping(value = "/captcha", produces = "application/json;charset=utf-8")
public class CaptchaController {

    private final StringRedisUtils stringRedisUtils;
    private final CaptchaImageProperties captchaImageProperties;

    @Autowired
    public CaptchaController(StringRedisUtils stringRedisUtils, CaptchaImageProperties captchaImageProperties) {
        this.stringRedisUtils = stringRedisUtils;
        this.captchaImageProperties = captchaImageProperties;
    }

    /**
     * 生成验证码
     *
     * @param type 验证码图片类型
     * @param uuid 前端生成的uuid
     */
    @RequestMapping(value = "/generate", method = RequestMethod.GET)
    public void generate(@RequestParam String type, @RequestParam String uuid) throws IOException {
        Captcha captcha;
        Integer width = captchaImageProperties.getWidth();
        Integer height = captchaImageProperties.getHeight();

        captcha = switch (type) {
            case "png" -> new SpecCaptcha(width, height);
            case "gif" -> new GifCaptcha(width, height);
            default -> throw new GlobalException(ResponseCode.BAD_REQUEST, "不合法的验证码类型：" + type);
        };

        captcha.setLen(captchaImageProperties.getLength());
        captcha.setCharType(Captcha.TYPE_DEFAULT);

        String code = captcha.text();
        log.debug("生成的验证码：{}", code);

        String key = RedisKeyPrefixes.PREFIX_CAPTCHA + uuid;
        // 缓存验证码
        stringRedisUtils.set(key, code);
        // 设置验证码3分钟后过期
        stringRedisUtils.expire(key, 3, TimeUnit.MINUTES);

        // 获取HttpServletResponse对象
        HttpServletResponse response = getResponse();

        // 设置请求头
        response.setContentType("image/" + type);
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        // 输出图片流
        captcha.out(response.getOutputStream());
    }

    /**
     * 获取HttpServletResponse对象
     *
     * @return HttpServletResponse
     */
    private HttpServletResponse getResponse() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        if (attributes != null) {
            HttpServletResponse response = ((ServletRequestAttributes) attributes).getResponse();

            if (response != null) {
                // 设置内容类型为json
                response.setContentType("application/json;charset=utf-8");

                return response;
            }
        }

        throw new GlobalException(ResponseCode.ERROR, "获取response对象失败");
    }

}